<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keywords" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="searchTest">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="updatPage">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="batchRemove">批量删除</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="department.rows" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="部门id">
              <span v-if="props.row.id">{{ props.row.id }}</span>
            </el-form-item>
            <el-form-item label="部门名称">
              <span v-if="props.row.name">{{ props.row.name }}</span>
            </el-form-item>

<!--            <el-form-item label="父级部门">-->
<!--              <span v-if="props.row.parent.name ==null">{{ props.row.parent.name}}</span>-->
<!--            </el-form-item>-->

            <el-form-item label="部门创建时间">
              <span v-if="props.row.createTime">{{ props.row.createTime }}</span>
            </el-form-item>
            <el-form-item label="部门修改时间">
              <span v-if="props.row.updateTime">{{ props.row.updateTime }}</span>
            </el-form-item>
            <el-form-item label="部门经理">
              <span v-if="props.row.manager.username">{{ props.row.manager.username }}</span>
            </el-form-item>
            <el-form-item label="部门状态">
              <span v-if="props.row.state">{{ props.row.state }}</span>
            </el-form-item>
            <el-form-item label="部门介绍">
              <span v-if="props.row.intro">{{ props.row.intro }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>


			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="180" >
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父级部门" width="80" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" min-width="80" sortable>
			</el-table-column>
      <el-table-column prop="state" label="state" min-width="80" sortable>

        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">启用</span>
          <span v-else style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="path" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="intro" label="intro" min-width="180" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button  size="small" @click="editPage(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

        <!--工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="query.pageSize"
        :current-page="query.currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="department.total">
    </el-pagination>

<!--新增-->

		<el-dialog title="新增/修改"  :visible.sync="dialogFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">

        <el-form-item label="部门名字" label-width="60" prop="name">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门经理" label-width="60">
<!--          <el-input v-model="addForm.manager.id" autocomplete="off"></el-input>-->


          <el-form-item label="" prop="manager">
            <el-select v-model="addForm.manager" clearable value-key="id" placeholder="请选择">
              <!--下拉选项
                :key=""  //唯一标识
                :label 选择之后展示到选择框中的值
                :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                   必须要写  value-key="id"
              -->
              <el-option
                  v-for="item in employees"
                  :key="item.id"
                  :label="item.username"
                  :value="item">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
              </el-option>
            </el-select>
          </el-form-item>

        </el-form-item>

        <el-form-item label="父级部门" label-width="60">

            <el-cascader v-model="addForm.parent"
                         :options="deptTree"
                         :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}" clearable >
            </el-cascader>
        </el-form-item>

				<el-form-item label="状态">
					<el-radio-group v-model="addForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="intro">
					<el-input type="textarea" v-model="addForm.intro"></el-input>
				</el-form-item>
			</el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reDate">取 消</el-button>
        <el-button type="primary" @click="addAndUpdate">确 定</el-button>
      </div>
		</el-dialog>


  </section>

</template>

<script>




  export default {
		data() {
			return {

				department:{
          rows: [],
          total: 0,
        },

				listLoading: false,
				sels: [],//列表选中列

        dialogFormVisible:false,

			//校验表单规则
				addFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					]
				},
				//新增界面数据
        addForm: {
          id:null,
          name: '',
          manager:{
            id:null,
            username:''
          },
          parent:{
            id:null,
            name:''
          },

          intro: ''
				},

        query:{
          currentPage:1,
          pageSize:10,
          keywords:""
        },
        //部门下拉框数据
        options:[
          {
            id:1,
            name:"请选择"
          }
        ],
        key:'',
        employees:[],
        deptTree:[],

			}
		},
		methods: {
      //取消，刷新页面
      reDate(){
        this.dialogFormVisible=false
        this.departmentInfo();
        this.addForm={
          id:null,
          name: '',
          manager:{
            id:null,
            username:''
          },
          parent:{
            id:null,
            name:''
          },
          intro: ''
        }
      },
		  //显示部门经理数据
      getAllEmployees(){
        this.$http.get("/employee")
                  .then(result =>{
                    result=result.data;
                    if(result.success){
                      this.employees=result.object;
                    }
                  })
                  .catch(result =>{
                  })
      },
      //显示新增界面
      updatPage(){
        this.getAllEmployees()
        this.addForm={
          id:null,
          name: '',
              manager:{
            id:null,
                username:''
          },
          parent:{
            id:null,
                name:''
          },
          intro: ''
        },
        this.dialogFormVisible=true;
        this.getDeptData()
      },
      //编辑回显
      editPage(index,row){
        let split=row.path.split("/")
        let arry=[]
        for (let i = 1; i <split.length-1 ; i++) {
         arry[i-1]=parseInt(split[i])
        }
        row.parent=arry
        this.dialogFormVisible=true;
        this.addForm=row
        this.getAllEmployees();
        this.getDeptData()
      },

      //获取部门数据
      getDeptData(){
        this.$http.get("/department/tree")
                  .then(result=>{
                    result=result.data;
                    if(result.success){
                      this.deptTree=result.object
                    }
                  })
            .catch(result={
        })
      },
    //新增部门数据
      addAndUpdate: function () {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              let para = Object.assign({}, this.addForm);
              //处理部门数据
              if(!para.parent){
                para.parent={
                  id:null
                }
              }else {
                para.parent={id:para.parent[para.parent.length-1]}
                }
              if(!para.manager){
                para.manager={
                  id:null
                }
              }
              this.$http.put("/department",para)
                  .then(result=>{
                    result=result.data;
                    if(result.success){
                      this.$message({type: 'success',message:result.message});
                    }else {
                      this.$message({type: 'error',message:result.message});
                    }
                    this.dialogFormVisible=false;
                    this.query.currentPage=1;
                    this.departmentInfo();
                  })
                  .catch(result=>{
                    this.$message({type: 'error',message:"网络出错了"});
                  })
            });
          }
        });
      },

		  //查询搜索
      searchTest(){
        this.query.currentPage=1;
        this.departmentInfo()

      },
			//监听当前页面所需展示条数
      handleSizeChange(val){
        this.query.currentPage = 1;
        this.query.pageSize=val;
        this.departmentInfo();
      },
      //监听当前页面索引
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.departmentInfo();
			},
			//获取部门列表
      departmentInfo() {
        this.$http.post("/department",this.query)
                  .then(res=>{
                    res=res.data;
                    this.department=res.object
                  })
        .catch(err=>{
          this.$message({
            message: '分页查询失败'+err.message,
            type: 'error'
          });
        })
			},
			//删除单个部门操作
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
				this.$http.delete("/department/"+row.id)
              .then(result =>{
                result=result.data
                this.listLoading = false;
            if(result.success){
              this.$message({message: '删除成功', type: 'success'});
              //刷新页面
              this.query.currentPage=1;
              this.departmentInfo();
            }else {
              this.$message({message: '删除失败'+result.message, type: 'error'});
            }
              })
		          .catch(errpr=>{
                this.$message({message: '网络出错', type: 'error'});
              })
				}).catch(() => {
          this.$message({message: '取消删除', type: 'info'});
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.dialogFormVisible = true;
        this.addForm=row
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
        if(this.sels.length ==0){
          this.$message({
            message: '未选择数据，请选择需要删除的数据后再操作',
            type: 'info'
          });
          return;
        }
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {

					this.$http.patch("/department",ids)
                  .then(result =>{
                    result=result.data;
                    if(result.success){
                      this.$message({
                        message: '批量删除成功',
                        type: 'success'
                      });
                      this.query.currentPage=1
                      this.departmentInfo()
                    }else {
                      this.$message({
                        message: '批量删除失败'+result.message,
                        type: 'error'
                      });
                    }
                  })
                  .catch(result=>{
                    this.$message({
                      message: '网络出错了',
                      type: 'error'
                    });
                  })
				}).catch(() => {
          this.$message({
            message: '取消删除',
            type: 'info'
          });
				});
			}
		},
		mounted() {
			this.departmentInfo();
		}
	}

</script>

<style scoped>

</style>